package com.banciyuan.bcywebview.base.app.crash;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.banciyuan.bcywebview.biz.start.StartActivity;

/**
 * Created by squall on 2015/8/3.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler instance;

    private Context context;

    private CrashHandler(){

    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {

        Intent intent = new Intent(context.getApplicationContext(), StartActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                context.getApplicationContext(), 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        //退出程序
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500,
                restartIntent); // 1秒钟后重启应用
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static CrashHandler getInstance(){

        if(null!=instance){
            return  instance;
        }else{
            instance=new CrashHandler();
            return  instance;
        }
    }

    public void init(Context context){
        this.context=context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
}
